import Chart from 'chart.js/auto'
// Chart.js 清理工具
export class ChartCleanup {
  static async cleanupAllCharts() {
    try {
      // 动态导入Chart.js
      const { Chart } = await import('chart.js')
      
      // 获取所有canvas元素
      const canvases = document.querySelectorAll('canvas')
      
      // 清理所有Chart.js实例
      canvases.forEach(canvas => {
        try {
          if (canvas && canvas.id) {
            const chartInstance = Chart.getChart(canvas)
            if (chartInstance && typeof chartInstance.destroy === 'function') {
              // 先停止所有动画
              if (chartInstance.options && chartInstance.options.animation) {
                chartInstance.options.animation = false
              }
              
              // 清理数据
              if (chartInstance.data) {
                chartInstance.data.datasets = []
                chartInstance.data.labels = []
              }
              
              // 销毁实例
              chartInstance.destroy()
            }
          }
        } catch (error) {
          console.warn('Chart cleanup error for canvas:', canvas, error)
        }
      })
      
      // 清理全局Chart实例
      try {
        if (Chart.instances) {
          Object.keys(Chart.instances).forEach(key => {
            try {
              const instance = Chart.instances[key]
              if (instance && typeof instance.destroy === 'function') {
                instance.destroy()
              }
            } catch (error) {
              console.warn('Global chart cleanup error:', error)
            }
          })
        }
      } catch (error) {
        console.warn('Global chart instances cleanup failed:', error)
      }
      
      console.log('✅ All Chart.js instances cleaned up')
    } catch (error) {
      console.warn('Chart.js cleanup failed:', error)
    }
  }
  
  static cleanupChartInstance(chartInstance) {
    try {
      if (chartInstance && typeof chartInstance.destroy === 'function') {
        chartInstance.destroy()
        return true
      }
    } catch (error) {
      console.warn('Chart instance cleanup error:', error)
    }
    return false
  }
  
  static cleanupCanvas(canvas) {
    try {
      if (canvas && canvas.id) {
        // 尝试通过ID清理
        const chartInstance = Chart.getChart(canvas)
        if (chartInstance) {
          chartInstance.destroy()
          return true
        }
      }
    } catch (error) {
      console.warn('Canvas cleanup error:', error)
    }
    return false
  }
}

// 全局错误处理
window.addEventListener('error', (event) => {
  if (event.error && event.error.message && 
      (event.error.message.includes('Cannot read properties of undefined') ||
       event.error.message.includes('disabled') ||
       event.error.message.includes('chart.js'))) {
    console.warn('Detected Chart.js error, attempting cleanup...')
    ChartCleanup.cleanupAllCharts()
  }
})

// 未处理的Promise错误
window.addEventListener('unhandledrejection', (event) => {
  if (event.reason && event.reason.message && 
      (event.reason.message.includes('Cannot read properties of undefined') ||
       event.reason.message.includes('disabled') ||
       event.reason.message.includes('chart.js'))) {
    console.warn('Detected Chart.js promise error, attempting cleanup...')
    ChartCleanup.cleanupAllCharts()
  }
})

// 页面卸载时清理
window.addEventListener('beforeunload', () => {
  ChartCleanup.cleanupAllCharts()
})

export default ChartCleanup
